package com.yunchang.springboot.quatrz.job.error;

import com.amazonservices.mws.client.MwsUtl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yunchang.springboot.mapper.base.IBaseMwsReportLogMapper;
import com.yunchang.springboot.mapper.shop.AreaMapper;
import com.yunchang.springboot.mapper.shop.ShopMapper;
import com.yunchang.springboot.models.Area;
import com.yunchang.springboot.models.Shop;
import com.yunchang.springboot.models.log.BaseMwsReportLogDO;
import com.yunchang.springboot.scheduled.amazon.mws.report.detail.GetReportProcessDetail;
import com.yunchang.springboot.utils.CryptoUtil;
import com.yunchang.springboot.utils.DateUtil;
import lombok.Getter;
import lombok.Setter;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.xml.datatype.XMLGregorianCalendar;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author sjd
 * @date 2020/8/19 0030  19:27
 * @description:
 */
@DisallowConcurrentExecution
public class ReportReimbursementsErrorDateJob implements Job {
    @Resource
    GetReportProcessDetail getReportProcessDetail;

    @Resource
    IBaseMwsReportLogMapper baseMwsReportLogMapper;

    @Resource
    ShopMapper shopMapper;

    @Resource
    AreaMapper areaMapper;

    @Getter
    @Setter
    private String reportName;

    @Getter
    @Setter
    private String reportType;

    /**
     * 报告获取时间范围
     */
    @Getter
    @Setter
    private String timeScope;

    @Getter
    @Setter
    private Integer getReportArea;

    @Getter
    @Setter
    private Integer getHistoryTime;

    @Getter
    @Setter
    private Integer reportInfoId;

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    @Override
    public void execute(JobExecutionContext context) {
        try {
//            // 根据报告id获得错误日志集合，其中有报告名称及报告类型和时间范围
            List<BaseMwsReportLogDO> mwsReportLogList = baseMwsReportLogMapper.getMwsReportLogByReportInfoId(reportInfoId);
            for (BaseMwsReportLogDO mwsReportLog : mwsReportLogList) {
                // 根据错误日志中的sellerId和area获得具体的店铺和国家信息
                String sellerId = mwsReportLog.getSellerId();
                String countryCode = mwsReportLog.getCountryCode();
                //根据sellerId获得店铺信息
                Shop shop = shopMapper.getOneInfoBySellerId(sellerId);
                shop.setSellerId(CryptoUtil.decode(shop.getSellerId()));
                shop.setMwsAuthToken(CryptoUtil.decode(shop.getMwsAuthToken()));
                shop.setAwsAccessKeyId(CryptoUtil.decode(shop.getAwsAccessKeyId()));
                shop.setSecretKey(CryptoUtil.decode(shop.getSecretKey()));
                //根据area国家简称来获得国家信息
                Area area = areaMapper.getAreaByMWSCountryCode(countryCode);
                //将错误日志中的日期当做入参传入
                Map<String, XMLGregorianCalendar> reportTimeScopeMap = new HashMap<>(2);
                XMLGregorianCalendar reportBeginTime = MwsUtl.getDTF().newXMLGregorianCalendar();
                XMLGregorianCalendar reportEndTime = MwsUtl.getDTF().newXMLGregorianCalendar();
                LocalDateTime startDate = DateUtil.getLocalDateTime(mwsReportLog.getStartDate());
                reportBeginTime.setYear(startDate.getYear());
                reportBeginTime.setMonth(startDate.getMonthValue());
                reportBeginTime.setDay(startDate.getDayOfMonth());
                reportBeginTime.setTime(startDate.getHour(), startDate.getMinute(), startDate.getSecond());
                LocalDateTime endDate = DateUtil.getLocalDateTime(mwsReportLog.getEndDate());
                reportEndTime.setYear(endDate.getYear());
                reportEndTime.setMonth(endDate.getMonthValue());
                reportEndTime.setDay(endDate.getDayOfMonth());
                reportEndTime.setTime(endDate.getHour(), endDate.getMinute(), endDate.getSecond());
                reportTimeScopeMap.put("reportBeginTime", reportBeginTime);
                reportTimeScopeMap.put("reportEndTime", reportEndTime);
                //新增一条日志记录
                BaseMwsReportLogDO childMwsReportLog = new BaseMwsReportLogDO()
                        .setParentId(mwsReportLog.getId())
                        .setSellerId(sellerId)
                        .setCountryCode(countryCode)
                        .setReportInfoId(reportInfoId)
                        .setReportType(reportType)
                        .setAccessMethod(3)
                        .setStartDate(mwsReportLog.getStartDate())
                        .setEndDate(mwsReportLog.getEndDate())
                        .setCreateTime(DateUtil.getNowDateTime())
                        .setModifyTime(DateUtil.getNowDateTime())
                        .setIsDelete(0);
                saveRequiredNewLog(childMwsReportLog);
                //新增之后再从数据库中查找出这条数据，主要是为了获得自增id，确定唯一性
                BaseMwsReportLogDO mwsReportLogDO = baseMwsReportLogMapper.selectOne(
                        new LambdaQueryWrapper<BaseMwsReportLogDO>()
                                .eq(BaseMwsReportLogDO::getParentId, childMwsReportLog.getParentId())
                                .eq(BaseMwsReportLogDO::getSellerId, childMwsReportLog.getSellerId())
                                .eq(BaseMwsReportLogDO::getCountryCode, childMwsReportLog.getCountryCode())
                                .eq(BaseMwsReportLogDO::getReportInfoId, childMwsReportLog.getReportInfoId())
                                .eq(BaseMwsReportLogDO::getReportType, childMwsReportLog.getReportType())
                                .eq(BaseMwsReportLogDO::getAccessMethod, childMwsReportLog.getAccessMethod())
                                .eq(BaseMwsReportLogDO::getStartDate, childMwsReportLog.getStartDate())
                                .eq(BaseMwsReportLogDO::getEndDate, childMwsReportLog.getEndDate())
                                .eq(BaseMwsReportLogDO::getCreateTime,childMwsReportLog.getCreateTime())
                                .eq(BaseMwsReportLogDO::getModifyTime,childMwsReportLog.getModifyTime())
                                .eq(BaseMwsReportLogDO::getIsDelete, childMwsReportLog.getIsDelete()));
                // 异步调用获取报告方法
                getReportProcessDetail.reportDetail(reportName, reportInfoId, reportType,timeScope, reportTimeScopeMap, shop, area, mwsReportLogDO);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    void saveRequiredNewLog(BaseMwsReportLogDO childMwsReportLog) {
        baseMwsReportLogMapper.insert(childMwsReportLog);
    }
}
